package com.example.service;


import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Drug;
import com.example.entity.PrescriptionItem;
import com.example.exception.CustomException;
import com.example.mapper.DrugMapper;
import com.example.mapper.PrescriptionItemMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.example.common.enums.ResultCodeEnum.DRUG_BIND_ERROR;

/**
 * 药品表业务处理
 **/
@Service
public class DrugService {

    @Resource
    private DrugMapper drugMapper;
    @Resource
    private PrescriptionItemMapper prescriptionItemMapper;

    /**
     * 新增
     */
    public void add(Drug drug) {
        drugMapper.insert(drug);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        List<PrescriptionItem> prescriptionItems = prescriptionItemMapper.selectByDrugId(id);
        if(prescriptionItems != null && !prescriptionItems.isEmpty()){
            throw new CustomException(ResultCodeEnum.DRUG_BIND_ERROR);
        }
        drugMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            drugMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Drug drug) {
        drugMapper.updateById(drug);
    }

    /**
     * 根据ID查询
     */
    public Drug selectById(Integer id) {
        return drugMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Drug> selectAll(Drug drug) {
        return drugMapper.selectAll(drug);
    }

    /**
     * 分页查询
     */
    public PageInfo<Drug> selectPage(Drug drug, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Drug> list = drugMapper.selectAll(drug);
        return PageInfo.of(list);
    }

    public void downDrugCount(PrescriptionItem prescriptionItem) {
        //更新药品的库存数量
        //获取药品
        Drug drug = drugMapper.selectById(prescriptionItem.getDrugId());
        drug.setInventory(drug.getInventory() - prescriptionItem.getQuantity());
        drugMapper.updateById(drug);
    }

    public void upDrugCount(PrescriptionItem prescriptionItem) {
        //更新药品的库存数量
        //获取药品
        Drug drug = drugMapper.selectById(prescriptionItem.getDrugId());
        drug.setInventory(drug.getInventory() + prescriptionItem.getQuantity());
        drugMapper.updateById(drug);
    }
}